// pages/anxiety/sensory.js
const app = getApp();
const themeManager = require('../../utils/theme-manager');
const { storage } = require('../../utils/storage');

Page({
  data: {
    // 主题相关
    currentTheme: 'pink',
    themeColors: {},
    
    // 感官安抚工具
    sensoryTools: [
      {
        id: 'visual',
        name: '视觉安抚',
        icon: 'icon-eye',
        color: '#87CEEB',
        description: '通过视觉元素缓解焦虑',
        techniques: [
          {
            id: 'color-breathing',
            name: '色彩呼吸',
            description: '跟随色彩变化进行深呼吸',
            duration: 300,
            colors: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57']
          },
          {
            id: 'mandala',
            name: '曼陀罗冥想',
            description: '专注观察几何图案',
            duration: 600,
            patterns: ['circle', 'flower', 'star', 'spiral']
          },
          {
            id: 'nature-scenes',
            name: '自然场景',
            description: '观看舒缓的自然画面',
            duration: 900,
            scenes: ['forest', 'ocean', 'mountain', 'garden']
          }
        ]
      },
      {
        id: 'auditory',
        name: '听觉安抚',
        icon: 'icon-music',
        color: '#DDA0DD',
        description: '通过声音元素放松心情',
        techniques: [
          {
            id: 'nature-sounds',
            name: '自然音效',
            description: '聆听大自然的声音',
            duration: 600,
            sounds: ['rain', 'ocean', 'forest', 'birds']
          },
          {
            id: 'white-noise',
            name: '白噪音',
            description: '稳定的背景音帮助专注',
            duration: 900,
            types: ['white', 'pink', 'brown', 'blue']
          },
          {
            id: 'binaural',
            name: '双耳节拍',
            description: '特定频率促进放松',
            duration: 1200,
            frequencies: ['alpha', 'theta', 'delta']
          }
        ]
      },
      {
        id: 'tactile',
        name: '触觉安抚',
        icon: 'icon-hand',
        color: '#98FB98',
        description: '通过触觉刺激缓解紧张',
        techniques: [
          {
            id: 'pressure-points',
            name: '穴位按摩',
            description: '按摩特定穴位缓解焦虑',
            duration: 300,
            points: ['temples', 'wrists', 'neck', 'shoulders']
          },
          {
            id: 'progressive-relaxation',
            name: '渐进式放松',
            description: '逐步放松全身肌肉',
            duration: 900,
            bodyParts: ['head', 'shoulders', 'arms', 'torso', 'legs']
          },
          {
            id: 'self-hug',
            name: '自我拥抱',
            description: '给自己温暖的拥抱',
            duration: 180,
            techniques: ['butterfly', 'bear', 'gentle']
          }
        ]
      },
      {
        id: 'olfactory',
        name: '嗅觉安抚',
        icon: 'icon-flower',
        color: '#F0E68C',
        description: '通过香气调节情绪',
        techniques: [
          {
            id: 'aromatherapy',
            name: '芳香疗法',
            description: '想象舒缓的香气',
            duration: 600,
            scents: ['lavender', 'chamomile', 'eucalyptus', 'vanilla']
          },
          {
            id: 'breathing-scents',
            name: '香气呼吸',
            description: '结合香气进行深呼吸',
            duration: 300,
            combinations: ['mint-fresh', 'floral-calm', 'woody-grounding']
          }
        ]
      }
    ],
    
    // 当前状态
    selectedTool: null,
    selectedTechnique: null,
    isActive: false,
    isPaused: false,
    currentStep: 0,
    totalSteps: 0,
    sessionTime: 0,
    
    // 动画状态
    animationData: {},
    currentColor: '#87CEEB',
    currentPattern: 'circle',
    currentScene: 'forest',
    
    // 音频状态
    audioContext: null,
    currentVolume: 0.5,
    
    // 统计数据
    sessionStats: {
      completedSessions: 0,
      totalTime: 0,
      favoriteTools: [],
      effectivenessRating: 0
    },
    
    // UI状态
    showToolSelector: false,
    showTechniqueDetail: false,
    showSettings: false,
    showStats: false,
    showRating: false,
    
    // 设置
    settings: {
      autoNext: true,
      vibrationEnabled: true,
      soundEnabled: true,
      defaultDuration: 600
    },
    
    // 定时器
    timer: null,
    animationTimer: null
  },

  onLoad(options) {
    this.initTheme();
    this.loadSettings();
    this.loadStats();
    
    // 如果有指定工具，直接显示
    if (options.tool) {
      const tool = this.data.sensoryTools.find(t => t.id === options.tool);
      if (tool) {
        this.setData({ selectedTool: tool });
      }
    }
  },

  onUnload() {
    this.stopSession();
  },

  // 初始化主题
  initTheme() {
    const userInfo = app.globalData.userInfo || {};
    const theme = userInfo.role === 'male' ? 'gold' : 'pink';
    const colors = themeManager.getThemeColors(theme);
    
    this.setData({
      currentTheme: theme,
      themeColors: colors
    });
  },

  // 加载设置
  loadSettings() {
    // 修复：正确访问存储对象
    const settings = storage.get('sensorySettings') || this.data.settings;
    this.setData({ settings });
  },

  // 加载统计
  loadStats() {
    // 修复：正确访问存储对象
    const stats = storage.get('sensoryStats') || this.data.sessionStats;
    this.setData({ sessionStats: stats });
  },

  // 选择工具
  onSelectTool(e) {
    const tool = e.currentTarget.dataset.tool;
    this.setData({
      selectedTool: tool,
      selectedTechnique: null,
      showToolSelector: false
    });
  },

  // 选择技巧
  onSelectTechnique(e) {
    const technique = e.currentTarget.dataset.technique;
    this.setData({
      selectedTechnique: technique,
      totalSteps: this.calculateSteps(technique),
      currentStep: 0
    });
  },

  // 计算步骤数
  calculateSteps(technique) {
    const baseSteps = Math.ceil(technique.duration / 30); // 每30秒一个步骤
    return Math.max(3, Math.min(20, baseSteps)); // 限制在3-20步之间
  },

  // 开始会话
  onStartSession() {
    if (!this.data.selectedTechnique) {
      wx.showToast({
        title: '请选择一个技巧',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isActive: true,
      isPaused: false,
      currentStep: 0,
      sessionTime: 0
    });

    this.startSession();
  },

  // 开始会话逻辑
  startSession() {
    const { selectedTechnique, totalSteps } = this.data;
    const stepDuration = selectedTechnique.duration / totalSteps;

    this.executeStep();
    
    this.data.timer = setInterval(() => {
      if (this.data.isPaused) return;

      const sessionTime = this.data.sessionTime + 1;
      this.setData({ sessionTime });

      // 检查是否需要进入下一步
      const expectedStep = Math.floor(sessionTime / stepDuration);
      if (expectedStep > this.data.currentStep && expectedStep < totalSteps) {
        this.setData({ currentStep: expectedStep });
        this.executeStep();
      }

      // 会话结束
      if (sessionTime >= selectedTechnique.duration) {
        this.completeSession();
      }
    }, 1000);
  },

  // 执行当前步骤
  executeStep() {
    const { selectedTool, selectedTechnique, currentStep } = this.data;
    
    switch (selectedTool.id) {
      case 'visual':
        this.executeVisualStep();
        break;
      case 'auditory':
        this.executeAuditoryStep();
        break;
      case 'tactile':
        this.executeTactileStep();
        break;
      case 'olfactory':
        this.executeOlfactoryStep();
        break;
    }

    // 震动反馈
    if (this.data.settings.vibrationEnabled) {
      wx.vibrateShort();
    }
  },

  // 执行视觉步骤
  executeVisualStep() {
    const { selectedTechnique, currentStep } = this.data;
    
    if (selectedTechnique.id === 'color-breathing') {
      const colors = selectedTechnique.colors;
      const colorIndex = currentStep % colors.length;
      this.setData({ currentColor: colors[colorIndex] });
      this.animateColorBreathing();
    } else if (selectedTechnique.id === 'mandala') {
      const patterns = selectedTechnique.patterns;
      const patternIndex = currentStep % patterns.length;
      this.setData({ currentPattern: patterns[patternIndex] });
      this.animateMandala();
    } else if (selectedTechnique.id === 'nature-scenes') {
      const scenes = selectedTechnique.scenes;
      const sceneIndex = currentStep % scenes.length;
      this.setData({ currentScene: scenes[sceneIndex] });
    }
  },

  // 执行听觉步骤
  executeAuditoryStep() {
    // 这里可以添加音频播放逻辑
    // 由于小程序限制，这里主要是UI提示
    const { selectedTechnique } = this.data;
    
    if (this.data.settings.soundEnabled) {
      // 播放对应的音效
      this.playAudioCue(selectedTechnique.id);
    }
  },

  // 执行触觉步骤
  executeTactileStep() {
    const { selectedTechnique, currentStep } = this.data;
    
    // 显示触觉指导
    this.showTactileGuidance(selectedTechnique, currentStep);
  },

  // 执行嗅觉步骤
  executeOlfactoryStep() {
    const { selectedTechnique, currentStep } = this.data;
    
    // 显示嗅觉引导
    this.showOlfactoryGuidance(selectedTechnique, currentStep);
  },

  // 色彩呼吸动画
  animateColorBreathing() {
    // 创建颜色渐变动画
    const animation = wx.createAnimation({
      duration: 4000,
      timingFunction: 'ease-in-out'
    });
    
    animation.scale(1.2).opacity(0.8).step();
    animation.scale(1).opacity(1).step();
    
    this.setData({ animationData: animation.export() });
  },

  // 曼陀罗动画
  animateMandala() {
    const animation = wx.createAnimation({
      duration: 6000,
      timingFunction: 'linear'
    });
    
    animation.rotate(360).step();
    this.setData({ animationData: animation.export() });
  },

  // 播放音频提示
  playAudioCue(techniqueId) {
    // 这里可以使用 wx.createInnerAudioContext() 播放音效
    // 由于需要音频文件，这里只是示例
  },

  // 显示触觉指导
  showTactileGuidance(technique, step) {
    let guidance = '';
    
    if (technique.id === 'pressure-points') {
      const points = technique.points;
      const point = points[step % points.length];
      guidance = this.getTactileGuidanceText(point);
    } else if (technique.id === 'progressive-relaxation') {
      const bodyParts = technique.bodyParts;
      const part = bodyParts[step % bodyParts.length];
      guidance = `放松你的${this.getBodyPartName(part)}`;
    }
    
    // 显示指导文本
    wx.showToast({
      title: guidance,
      icon: 'none',
      duration: 3000
    });
  },

  // 显示嗅觉引导
  showOlfactoryGuidance(technique, step) {
    let guidance = '';
    
    if (technique.id === 'aromatherapy') {
      const scents = technique.scents;
      const scent = scents[step % scents.length];
      guidance = `想象${this.getScentName(scent)}的香气`;
    }
    
    wx.showToast({
      title: guidance,
      icon: 'none',
      duration: 3000
    });
  },

  // 获取触觉指导文本
  getTactileGuidanceText(point) {
    const texts = {
      temples: '轻柔按摩太阳穴',
      wrists: '按压手腕内侧',
      neck: '轻抚颈部两侧',
      shoulders: '放松肩膀肌肉'
    };
    return texts[point] || '深呼吸放松';
  },

  // 获取身体部位名称
  getBodyPartName(part) {
    const names = {
      head: '头部',
      shoulders: '肩膀',
      arms: '手臂',
      torso: '躯干',
      legs: '腿部'
    };
    return names[part] || part;
  },

  // 获取香气名称
  getScentName(scent) {
    const names = {
      lavender: '薰衣草',
      chamomile: '洋甘菊',
      eucalyptus: '桉树',
      vanilla: '香草'
    };
    return names[scent] || scent;
  },

  // 暂停/恢复
  onTogglePause() {
    const isPaused = !this.data.isPaused;
    this.setData({ isPaused });
  },

  // 停止会话
  onStopSession() {
    this.stopSession();
    this.saveSession();
    this.setData({ showRating: true });
  },

  // 停止会话逻辑
  stopSession() {
    this.setData({
      isActive: false,
      isPaused: false,
      currentStep: 0
    });

    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    if (this.data.animationTimer) {
      clearInterval(this.data.animationTimer);
    }
  },

  // 完成会话
  completeSession() {
    this.stopSession();
    this.saveSession();
    this.setData({ showRating: true });
    
    wx.showToast({
      title: '会话完成！',
      icon: 'success'
    });
  },

  // 保存会话
  saveSession() {
    const { selectedTool, selectedTechnique, sessionTime } = this.data;
    
    const sessionData = {
      tool: selectedTool.name,
      technique: selectedTechnique.name,
      duration: sessionTime,
      timestamp: Date.now()
    };

    // 更新统计
    const stats = { ...this.data.sessionStats };
    stats.completedSessions++;
    stats.totalTime += sessionTime;
    
    // 更新喜爱工具
    const toolIndex = stats.favoriteTools.findIndex(t => t.id === selectedTool.id);
    if (toolIndex >= 0) {
      stats.favoriteTools[toolIndex].count++;
    } else {
      stats.favoriteTools.push({ id: selectedTool.id, name: selectedTool.name, count: 1 });
    }
    
    this.setData({ sessionStats: stats });
    storage.set('sensoryStats', stats);
    
    // 保存会话记录
    const sessions = storage.get('sensorySessions') || [];
    sessions.unshift(sessionData);
    if (sessions.length > 50) {
      sessions.splice(50);
    }
    storage.set('sensorySessions', sessions);
  },

  // 评分
  onRateEffectiveness(e) {
    const rating = parseInt(e.currentTarget.dataset.rating);
    const stats = { ...this.data.sessionStats };
    stats.effectivenessRating = rating;
    
    this.setData({ 
      sessionStats: stats,
      showRating: false 
    });
    
    storage.set('sensoryStats', stats);
    
    wx.showToast({
      title: '感谢您的反馈！',
      icon: 'success'
    });
  },

  // 显示工具选择器
  onShowToolSelector() {
    this.setData({ showToolSelector: true });
  },

  // 显示技巧详情
  onShowTechniqueDetail(e) {
    const technique = e.currentTarget.dataset.technique;
    this.setData({
      selectedTechnique: technique,
      showTechniqueDetail: true
    });
  },

  // 显示设置
  onShowSettings() {
    this.setData({ showSettings: true });
  },

  // 显示统计
  onShowStats() {
    this.setData({ showStats: true });
  },

  // 切换设置
  onToggleSetting(e) {
    const { setting } = e.currentTarget.dataset;
    const settings = { ...this.data.settings };
    settings[setting] = !settings[setting];
    
    this.setData({ settings });
    storage.set('sensorySettings', settings);
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showToolSelector: false,
      showTechniqueDetail: false,
      showSettings: false,
      showStats: false,
      showRating: false
    });
  },

  // 格式化时间
  formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  },

  // 获取进度百分比
  getProgress() {
    const { currentStep, totalSteps } = this.data;
    return totalSteps > 0 ? Math.round((currentStep / totalSteps) * 100) : 0;
  },

  onShareAppMessage() {
    return {
      title: '感官安抚 - 多维度缓解焦虑',
      path: '/pages/anxiety/sensory',
      imageUrl: '/images/sensory-share.png'
    };
  }
});